﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System.ComponentModel.Composition;
using System.IO.IsolatedStorage;
using Caliburn.Micro;
using OI.Framework;

namespace OIManager.ViewModels
{
    [Export(typeof (SettingsViewModel))]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class SettingsViewModel : Screen
    {
        private const string SQLConnectionKey = "SQLConnection";


        // Create an instance of IsolatedStorageSettings.
        private readonly IsolatedStorageSettings _UserSettings =
            IsolatedStorageSettings.ApplicationSettings;

        private string _SQLConnection;


        [ImportingConstructor]
        public SettingsViewModel()
        {
            base.DisplayName = "Settings";
        }

        // determine whether this is a start-up dialog or shell view
        public bool IsContextShell
        {
            get { return Parent is IShell; }
        }


        // are the settings set
        public bool AreSettingsSet
        {
            get
            {
                return !string.IsNullOrEmpty(SQLConnection);
            }
        }


        // by convention
        // admin sql connection
        public string SQLConnection
        {
            get
            {
                if (_SQLConnection == null)
                {
                    _UserSettings.TryGetValue(SQLConnectionKey, out _SQLConnection);
                }
                return _SQLConnection;
            }
            set
            {
                _SQLConnection = value;
                NotifyOfPropertyChange(() => CanSave);
            }
        }


        // by convention
        public bool CanSave
        {
            get
            {
                string sc;
                _UserSettings.TryGetValue(SQLConnectionKey, out sc);
                bool dataDirty = sc != SQLConnection;

                return AreSettingsSet && dataDirty;
            }
        }


        // by convention
        public void Save()
        {
            _UserSettings[SQLConnectionKey] = (SQLConnection ?? "");
            NotifyOfPropertyChange(() => CanSave);

            if (!IsContextShell)
            {
                TryClose();
            }
        }
    }
}